import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BasicDynaClass;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.WrapDynaBean;
import org.junit.Test;

public class BeanTest {
	@Test
	public void test1() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		Dog dog = new Dog("red");
		//通过PropertyUtils来修改color的值
		PropertyUtils.setSimpleProperty(dog, "color", "yellow");
		System.out.println(PropertyUtils.getSimpleProperty(dog, "color"));
		
		// 通过反射机制实现取值
		DynaBean bean = new WrapDynaBean(dog);
		System.out.println(bean.get("color"));
		bean.set("color", "green");
		System.out.println(dog);

		Map<String, Object> map = new HashMap<String, Object>(0);
		map.put("color", "blue");
		try {
			// 将map中的值映射到实体类中
			BeanUtils.populate(dog, map);
			System.out.println(dog);
			// 将实体类中的值映射到map中
			Map<String, String> map1 = BeanUtils.describe(dog);
			System.out.println(map1.get("color"));
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void test2() {

		DynaProperty[] props = new DynaProperty[3];
		props[0] = new DynaProperty("age", int.class);
		props[1] = new DynaProperty("color", String.class);
		props[2] = new DynaProperty("dog", Dog.class);
		BasicDynaClass dynaClass = new BasicDynaClass("employee", null, props);
		DynaBean employee = null;
		try {
			employee = dynaClass.newInstance();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
		employee.set("age", 1);
		employee.set("color", "blue");
		employee.set("dog", new Dog("blue"));
	}
	
	@Test
	public void test3(){
		Map<String, Object> map = new HashMap<String, Object>(0);
		map.put("dog", new Dog("blue"));
		Dog dog = (Dog) map.get("dog");
	}
}
